package br.com.trumah.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.trumah.dao.interfaces.DependenteDAO;
import br.com.trumah.model.Dependente;
import br.com.trumah.utils.HibernateUtil;

public class DependentesDAOImpl implements DependenteDAO {
	
	private Session session = null;
	private Transaction t = null;

	@Override
	public void salvar(Dependente dependente) {
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.save(dependente);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}


	}

	@Override
	public Dependente obterDependente(long id) {
		Dependente dependente = null;
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			dependente = (Dependente) session.load(Dependente.class, id);
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return dependente;
		
	}

	@Override
	public List<Dependente> listar() {
		
		List<Dependente> lista = null;
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			lista = session.createQuery("from Dependente").list();
			t.commit();
			
		} catch (HibernateException ex) {
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return lista;
		
	}

	@Override
	public void remover(Dependente dependente) {

		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.delete(dependente);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		

	}

	@Override
	public void atualizar(Dependente dependente) {
		
		try {

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.update(dependente);
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}


	}

}
